import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

/// 图片组件
class ImageWidget extends StatelessWidget {
  /// 图片路径
  final String path;

  /// 图片大小
  final double? size;

  /// 自定义宽度
  final double? width;

  /// 自定义高度
  final double? height;

  /// 图片圆角
  final double? radius;

  /// 如何将图像刻入布局时分配的空间
  final BoxFit fit;

  /// 错误图片
  final String? errorUrl;

  /// 错误占位图
  final Widget? errorImage;
  const ImageWidget(
    this.path, {
    super.key,
    this.size,
    this.radius,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.errorUrl,
    this.errorImage,
  });

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      clipBehavior: Clip.antiAlias,
      borderRadius: BorderRadius.circular(radius ?? 0),
      child: getImage(),
    );
  }

  /// 获取图片
  Widget getImage() {
    if (path.startsWith("http")) {
      return networkImage();
    } else if (path.startsWith("assets")) {
      return assetsImage();
    } else {
      File file = File(path);
      if (!file.existsSync()) {
        return errorCard();
      }
      return fileImage();
    }
  }

  /// 本地图片
  Widget assetsImage() {
    return Image.asset(
      path,
      width: size ?? width,
      height: size ?? height,
      fit: fit,
    );
  }

  /// 文件图片
  Widget fileImage() {
    return Image.file(
      File(path),
      width: size ?? width,
      height: size ?? height,
      fit: fit,
    );
  }

  /// 网络图片
  Widget networkImage() {
    return CachedNetworkImage(
      imageUrl: path,
      width: size ?? width,
      height: size ?? height,
      fit: fit,
      progressIndicatorBuilder: (context, url, downloadProgress) {
        return CircularProgressIndicator(value: downloadProgress.progress);
      },
    );
  }

  /// 错误占位图
  Widget errorCard() {
    double? width = size ?? this.width;
    double? height = size ?? this.height;
    return Container(
      width: width,
      height: height,
      color: const Color.fromRGBO(1, 1, 0, 0.5),
      child: FractionallySizedBox(
        widthFactor: 0.7,
        heightFactor: 0.7,
        child: errorImage ??
            Image.asset(
              errorUrl ?? "assets/images/icons/not_image.png",
              color: Colors.white,
            ),
      ),
    );
  }
}
